<template>
  <div class="fillInTheContract-container">
    <!-- 合同的html -->
    <div
      :class="[
        rightBoxState.hideRightBoxFlag
          ? 'contract-wrapper hide-contract-wrapper-width'
          : 'contract-wrapper show-contract-wrapper-width',
      ]"
    >
      <div
        ref="previewBoxRef"
        id="demoDocContainer"
        class="previewBox"
        :style="{ height: 1200 + 'px', width: '100%' }"
        v-html="html"
      ></div>
      <div class="button-wrapper">
        <el-button @click="goCollaborativeApproval" class="button_edit">重新选择合同模板</el-button>
        <el-button @click="saveAndNext" class="button_view">保存并下一步</el-button>
      </div>
    </div>

    <!--  右侧固定参数box    -->
    <div
      class="rightBox"
      :class="
        rightBoxState.hideRightBoxFlag ? 'hideRightWidth' : 'showRightWidth'
      "
    >
      <div
        class="ctrlBtnBox"
        :class="rightBoxState.hideRightBoxFlag ? 'toLeftBtn' : 'toLeftBtn'"
        @click="doControlRight"
      >
        <el-icon :size="20" v-if="!rightBoxState.hideRightBoxFlag"
          ><ArrowRight
        /></el-icon>
        <el-icon :size="20" v-else><ArrowLeft /></el-icon>
      </div>
      <div
        class="formHeadBox"
        :style="
          rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
            ? 'display:none'
            : !rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
            ? 'display:none'
            : ''
        "
      >
        固定参数设置
      </div>
      <el-form
        :model="form"
        ref="formRef"
        :rules="formRules.rules"
        label-width="121px"
        :style="
          rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
            ? 'display:none'
            : !rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
            ? 'display:none'
            : ''
        "
      >
      <el-form-item label="新签/续签" prop="signType">
          <el-select
                  v-model="form.signType"
                  class="selectStyle"
                  placeholder="请选择"
                  @change="signTypeChange"
          >
              <el-option
                      v-for="item in signTypeOptionsArr"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
              >
              </el-option>
          </el-select>
      </el-form-item>
        <el-form-item label="承租方(乙方)" prop="haveCustomerValFlag">
          <el-input
            class="inputStyle"
            v-model="form.haveCustomerValFlag"
            placeholder="点击选择"
            readonly
            @click="showTenantryDialog('leaseCustomers')"
          />
        </el-form-item>
        <!-- 选择的租赁方客户 -->
        <div class="housesListBox" v-if="form.leaseCustomers.length">
          <el-form-item
            class="housesItemStyle"
            v-for="(n, i) in form.leaseCustomers"
            :key="i"
            :label="`乙方${i + 1}`"
          >
            <img
              class="deletBtn"
              src="@/assets/iconImg/delet.png"
              alt=""
              @click="doDeleteLeaseCustomersList(i)"
            />
            <el-input
              v-model="n.customerName"
              placeholder="客户姓名"
              disabled
            />
          </el-form-item>
        </div>
        <el-form-item label="竞租方式" prop="competitionLeaseType">
          <el-select
            v-model="form.competitionLeaseType"
            class="selectStyle"
            placeholder="请选择"
            @change="competeTypeChange"
          >
            <el-option
              v-for="item in competeTypeOptionsArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="租赁的资产" prop="leaseAsset">
          <el-input
            class="inputStyle"
            v-model="form.leaseAsset"
            placeholder="点击选择"
            readonly
            @click="()=>{showAssetDialog();selectedDom('leaseHousings')}"
          />
        </el-form-item>
        <el-form-item label="租赁的房源" prop="haveHousingValFlag">
          <el-input
            class="inputStyle"
            v-model="form.haveHousingValFlag"
            :placeholder="form.leaseAsset===''?'请先选择租赁的资产':'点击选择'"
            readonly
            :disabled="form.leaseAsset===''"
            @click="()=>{showHousingDialog();selectedDom('leaseHousings')}"
          />
        </el-form-item>
        <!-- 选择的房源列表 -->
        <div class="housesListBox" v-if="form.leaseHousings.length">
          <el-form-item
            class="housesItemStyle"
            v-for="(n, i) in form.leaseHousings"
            :key="i"
            :label="`房源${i + 1}`"
          >
            <img
              class="deletBtn"
              src="@/assets/iconImg/delet.png"
              alt=""
              @click="doDeletHousesList(i)"
            />
            <el-input v-model="n.housingNumber" placeholder="门牌号" disabled />
            <el-input
              v-model="n.leaseArea"
              placeholder="租赁面积(平方米)"
              disabled
            />
          </el-form-item>
        </div>
        <el-form-item label="租赁总面积">
          <el-input
            v-model="form.leaseTotalArea"
            placeholder="点击选择"
            disabled
          />
        </el-form-item>
        <el-form-item class="limitInput" label="租赁期限" prop="sign_time">
          <el-date-picker
            v-model="form.sign_time"
            type="daterange"
            class="dateInputBox dateRangeBox"
            value-format="YYYY-MM-DD"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @change="onSignTimeChange"
            size="large"
          />
          <el-input
            v-model="form.signMonthlyRent"
            class="inputStyle"
            style="width: 45px"
            disabled
            placeholder="月"
          />
        </el-form-item>
        <el-form-item label="免租期" prop="freeRentMonth">
          <el-input
            v-model="form.freeRentMonth"
            class="inputStyle"
            placeholder="月数（单位：月）"
            clearable
            @click="selectedDom('freeRentMonth')"
            @input="
              form.freeRentMonth = limitInputNum(
                form.freeRentMonth,
                10,
                0,
                false
              )
            "
          />
        </el-form-item>
        <el-form-item label="经营用途" prop="businessPurpose">
          <el-input
            v-model="form.businessPurpose"
            class="inputStyle"
            maxlength="32"
            @click="selectedDom('businessPurpose')"
            placeholder="请输入经营用途"
            clearable
          />
        </el-form-item>
<!--        <el-form-item label="业态" prop="purpose">
          <el-input
            v-model="form.purpose"
            class="inputStyle"
            maxlength="32"
            placeholder="请输入业态"
            clearable
          />
        </el-form-item>-->
        <el-form-item label="租金单价" prop="areaUnitPrice">
          <el-input
            v-model="form.areaUnitPrice"
            class="inputStyle"
            placeholder="请输入金额（单位：元/㎡/月）"
            clearable
            @click="selectedDom('areaUnitPrice')"
            @input="
              form.areaUnitPrice = limitInputNum(form.areaUnitPrice, 9, 2, true)
            "
          />
        </el-form-item>
        <el-form-item label="递增模式和比例" class="modeItemBox" required>
          第
          <el-form-item label="" prop="increaseStartYear">
            <el-input
              v-model="form.increaseStartYear"
              class="inputStyle"
              placeholder="N"
              @click="selectedDom('increaseStartYear')"
              @input="
                form.increaseStartYear = limitInputNum(
                  form.increaseStartYear,
                  3,
                  0,
                  false
                )
              "
            />
          </el-form-item>
          年后，逐年递增
          <el-form-item label="" prop="increaseRate">
            <el-input
              v-model="form.increaseRate"
              class="inputStyle"
              placeholder="%"
              @click="selectedDom('increaseRate')"
              @input="
                form.increaseRate = limitInputNum(
                  form.increaseRate,
                  3,
                  0,
                  false
                )
              "
            />%
          </el-form-item>
        </el-form-item>
        <el-form-item label="付款方式" prop="payType">
          <el-select
            v-model="form.payType"
            class="selectStyle"
            placeholder="请选择付款方式"
            @change="payTypeChange"
          >
            <el-option
              v-for="item in payTypeOptionsArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物业管理费" prop="propertyCost">
          <el-input
            v-model="form.propertyCost"
            class="inputStyle"
            placeholder="请输入金额（单位：元/㎡/月）"
            clearable
            @click="selectedDom('propertyCost')"
            @input="
              form.propertyCost = limitInputNum(form.propertyCost, 9, 2, true)
            "
          />
        </el-form-item>
        <el-form-item label="租赁保证金" prop="deposit">
          <el-input
            v-model="form.deposit"
            class="inputStyle"
            placeholder="请输入租赁保证金金额（单位：元）"
            @input="form.deposit = limitInputNum(form.deposit, 9, 2, true)"

            @click="selectedDom('deposit')"
          />
<!--            @change="depositValueChange"-->
        </el-form-item>
        <el-form-item class="limitInput" label="保证金缴纳时间">
          <el-date-picker
            v-model="form.depositPayTime"
            class="dateInputBox"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="请选择租赁保证金缴纳日期"
            :disabled-date="payDisabledDate"
            size="large"
            @click="selectedDom('depositPayTime')"
          >
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label="履约保证金" prop="performanceBond">
          <el-input
            v-model="form.performanceBond"
            class="inputStyle"
            placeholder="请输入履约保证金金额（单位：元）"
            clearable
            @input="
              form.performanceBond = limitInputNum(
                form.performanceBond,
                9,
                2,
                true
              )
            "
          />
        </el-form-item>-->
        <el-form-item
          class="limitInput"
          label="履约金缴纳时间"
          prop="performanceTime"
        >
          <el-date-picker
            v-model="form.performanceTime"
            class="dateInputBox"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="请选择履约保证金缴纳日期"
            :disabled-date="payDisabledDate"
            size="large"
            @click="selectedDom('performanceTime')"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item class="limitInput" label="约定开始时间" prop="openTime">
          <el-date-picker
            v-model="form.openTime"
            class="dateInputBox"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="请选择开业日期"
            :disabled-date="openDisabledDate"
            size="large"
            @click="selectedDom('openTime')"
          >
          </el-date-picker>
        </el-form-item>
        <div v-if="contractTemplateId==='4'">
            <el-form-item label="期限" prop="term">
                <el-input
                        v-model="form.term"
                        class="inputStyle"
                        placeholder="请输入期限"
                        @click="selectedDom('term')"
                />
            </el-form-item>
            <el-form-item label="起始说明" prop="startDescription">
                <el-input
                        v-model="form.startDescription"
                        class="inputStyle"
                        @click="selectedDom('startDescription')"
                        placeholder="请输入起始说明"
                />
            </el-form-item>
            <el-form-item label="物业说明" prop="propertyDescription">
                <el-input
                        v-model="form.propertyDescription"
                        class="inputStyle"
                        placeholder="请输入物业说明"
                        @click="selectedDom('propertyDescription')"
                />
            </el-form-item>
            <el-form-item label="免租期说明" prop="explanationOfRentFreePeriod">
                <el-input
                        v-model="form.explanationOfRentFreePeriod"
                        class="inputStyle"
                        placeholder="请输入免租期说明"
                        @click="selectedDom('explanationOfRentFreePeriod')"
                />
            </el-form-item>
            <el-form-item label="方案" prop="programme">
                <el-input
                        v-model="form.programme"
                        class="inputStyle"
                        placeholder="请输入方案"
                        @click="selectedDom('programme')"
                />
            </el-form-item>
            <el-form-item label="廉洁说明" prop="integrityStatement">
                <el-input
                        v-model="form.integrityStatement"
                        class="inputStyle"
                        placeholder="请输入廉洁说明"
                        @click="selectedDom('integrityStatement')"
                />
            </el-form-item>
            <el-form-item label="业务单元" prop="businessUnit">
                <el-input
                        v-model="form.businessUnit"
                        class="inputStyle"
                        placeholder="请输入业务单元"
                        @click="selectedDom('businessUnit')"
                />
            </el-form-item>
            <el-form-item label="未办理证件" prop="failureToObtainDocuments">
                <el-input
                        v-model="form.failureToObtainDocuments"
                        class="inputStyle"
                        placeholder="请输入未办理证件"
                        @click="selectedDom('failureToObtainDocuments')"
                />
            </el-form-item>
            <el-form-item label="已办理证件" prop="documentsHaveBeenProcessed">
                <el-input
                        v-model="form.documentsHaveBeenProcessed"
                        class="inputStyle"
                        placeholder="请输入已办理证件"
                        @click="selectedDom('documentsHaveBeenProcessed')"
                />
            </el-form-item>
        </div>
        <el-form-item label="补充协议" prop="fileVoList">
            <FileMinioUpload
                    :restriction="true"
                    :restrictionLimit="9"
                    v-model:files="form.fileVoList"
            />
        </el-form-item>
      </el-form>
    </div>
  </div>

    <SelectLeaseAssetDialog
            ref="LeaseAssetDialogRef"
            @getAssetId="getAssetId"
    />
    <SelectLeaseHouseDialog
            ref="LeaseHouseDialogRef"
            @getHouseInfo="getHouseInfo"
    />
    <SelectTenantryDialog
            ref="TenantryDialogRef"
            @getTenantryInfo="getTenantryInfo"
    />
</template>

<script setup>
import {
    ElForm,
    ElFormItem,
    ElSelect,
    ElOption,
    ElDatePicker,
    ElMessage, ElLoading,
} from "element-plus";
import { ArrowRight, ArrowLeft } from "@element-plus/icons-vue";
import SelectLeaseAssetDialog from "@/views/assetManagement/companyContractManagement/templateManagement/components/selectLeaseAssetDialog";
import SelectLeaseHouseDialog from "@/views/assetManagement/companyContractManagement/templateManagement/components/selectLeaseHouseDialog";
import SelectTenantryDialog from "./SelectTenantryDialog";
import store from "@/store";
import {
  competeTypeOptionsArr,
  payTypeOptionsArr,
  signTypeOptionsArr,
} from "@/common/dict/dictCollect";
import { contractApi, otherApi } from "@/api/assets";
import { contractApi as contractApi2 } from "@/api/coordination";
import {nextTick, onMounted, reactive, ref, watch} from "vue";
import dayjs from "dayjs";
import {
    blobToFile,
    limitInputNum,
    localSet,
} from "@/common/utils/GlobalUtils";
import { useRouter } from "vue-router";
import FileMinioUpload from "@/components/FileMinioUpload.vue";
import {reserveInvestmentProjectLibraryApi} from "@/api/investment";
import {renderAsync} from "docx-preview";
//导入PDFObject
import PDFObject from 'pdfobject';


const html = ref("");
const params = reactive({
  assetId: "",
});

const router = useRouter();

// 从路由path中获取的
let getTemplateUrlKey = router.currentRoute.value.params.templateUrlKey;
const getContractId = router.currentRoute.value.params.id;


const initInfo = () => {
  contractApi.contractPreview(getTemplateUrlKey).then((res) => {
    if (!res.code) {
      html.value = res;
    /*  setTimeout(()=>{
          deleteDomText();
      },500)*/
      setTimeout(()=>{
          createDomNodes();
      },1000)
    }
  });
};

// form相关
const formRef = ref(null);
const form = reactive({
  customerName:'',// 占位属性
  fileVoList:[], // 补充协议
    contractId:'',
  haveCustomerValFlag: "", // 仅用于'承租方(乙方)'必填的提示
  haveHousingValFlag: "", // 仅用于'租赁的房源'必填的提示
  leaseCustomers: [], // 租赁客户List
  competitionLeaseType: "", // 竞租方式
  assetsId: "", // 资产编号
  leaseHousings: [], // 房源list
  leaseTotalArea: "", //租赁总面积
  signStartTime: "", // 租赁开始时间
  signEndTime: "", // 租赁结束时间
  signMonthlyRent: "", // 签约实际月租
  freeRentMonth: "", // 免租月数
  businessPurpose: "", // 经营用途
  purpose: "", // 业态
  areaUnitPrice: "", // 租金单价
  increaseStartYear: "", // 增幅开始第几年
  increaseRate: "", // 增幅比例（%）
  payType: "", // 支付方式（1，月，2 季，3 年）
  signType: "", // 签约类型(1新签2续签)
  propertyCost: "", // 物业管理费
  contractTemplateId: "", // 合同模板id
  assetsName: "", // 资产名字
  address: "", // 资产地址
  deposit: "0", // 租赁保证金(押金)
  depositPayTime: "", // 租赁保证金(押金支付时间)缴纳时间
  performanceBond: "", // 履约保证金
  performanceTime: "", // 履约保证金缴纳时间
  openTime: "", // 约定开始时间
  payeeId: "", // 银行账户id
  leaseAsset: "",
  selectedHousesArr: [],
  selectedLeaseCustomersArr: [],
  sign_time: "",
  term:'',
  startDescription:'',
  propertyDescription:'',
  explanationOfRentFreePeriod:'',
  programme:'',
  integrityStatement:'',
  businessUnit:'',
  fileOne:'',
  fileTwo:'',
  fileThree:'',
  failureToObtainDocuments:'',
  documentsHaveBeenProcessed:'',
});

// 校验
const formRules = reactive({
  rules: {
    haveCustomerValFlag: [
      { required: true, trigger: "change", message: "请选择承租方(乙方)" },
    ],
    haveHousingValFlag: [
      { required: true, trigger: "change", message: "请选择租赁的房源" },
    ],
    competitionLeaseType: [
      { required: true, trigger: "change", message: "请选择竟租方式" },
    ],
    leaseAsset: [
      { required: true, trigger: "change", message: "请选择租赁的资产" },
    ],
    sign_time: [
      { required: true, trigger: "change", message: "请选择租赁期限" },
    ],
    freeRentMonth: [
      { required: true, trigger: "blur", message: "请输入免租月数" },
    ],
    businessPurpose: [
      { required: true, trigger: "blur", message: "请输入经营用途" },
    ],
    // purpose: [{ required: true, trigger: "blur", message: "请输入业态" }],
    areaUnitPrice: [
      { required: true, trigger: "blur", message: "请输入租金单价" },
    ],
    increaseStartYear: [
      { required: true, trigger: "blur", message: "请输入年数" },
    ],
    increaseRate: [
      { required: true, trigger: "blur", message: "请输入递增比例" },
    ],
    payType: [{ required: true, trigger: "change", message: "请选择付款方式" }],
    propertyCost: [
      { required: true, trigger: "blur", message: "请输入物业管理费" },
    ],
    signType: [
      { required: true, trigger: "change", message: "请选择签约类型" },
    ],
    deposit: [
      { required: true, trigger: "blur", message: "请输入租赁保证金额" },
    ],
    /*depositPayTime: [
      { required: true, trigger: "change", message: "请选择缴纳时间" },
    ],*/
    openTime: [
      { required: true, trigger: "change", message: "请选择约定开始时间" },
    ],
     term: [
        { required: true, trigger: "blur", message: "请输入期限" },
    ],
    startDescription: [
        { required: true, trigger: "blur", message: "请输入起始说明" },
    ],
    propertyDescription: [
        { required: true, trigger: "blur", message: "请输入物业说明" },
    ],
    explanationOfRentFreePeriod: [
        { required: true, trigger: "blur", message: "请输入免租期说明" },
    ],
    programme: [
        { required: true, trigger: "blur", message: "请输入方案" },
    ],
    integrityStatement: [
        { required: true, trigger: "blur", message: "请输入廉洁说明" },
    ],
    businessUnit: [
        { required: true, trigger: "blur", message: "请输入业务单元" },
    ],
    fileOne: [
        { required: true, trigger: "change", message: "请上传营业执照" },
    ],
    fileTwo: [
        { required: true, trigger: "change", message: "请上传身份证" },
    ],
    fileThree: [
        { required: true, trigger: "change", message: "请上传租赁区域平面图" },
    ],
    failureToObtainDocuments: [
        { required: true, trigger: "change", message: "请输入未办理证件" },
    ],
    documentsHaveBeenProcessed: [
        { required: true, trigger: "change", message: "请输入已办理证件" },
    ],
  },
});

// 租赁保证金默认传 '0',此时缴纳时间非必填；
// 当其值不为'0'时，缴纳时间必填
const depositValueChange = (val) => {
  if (val !== "0") {
    formRules.rules.depositPayTime = [
      { required: true, trigger: "change", message: "请选择缴纳时间" },
    ];
  } else {
    if (formRules.rules.depositPayTime) {
      delete formRules.rules.depositPayTime;
      formRef.value.clearValidate("depositPayTime");
    }
  }
};

// 收起/展开 相关
const rightBoxState = reactive({
  hideRightBoxFlag: false, // 控制右侧整体
  hideRightCnFlag: false, // 控制右侧内容部分
});
// 收起/展开按钮点击
const doControlRight = () => {
  rightBoxState.hideRightBoxFlag = !rightBoxState.hideRightBoxFlag;
  if (rightBoxState.hideRightBoxFlag) {
    // 收起时
    setTimeout(() => {
      // 延时控制，解决收起时横向滚动条闪现问题
      rightBoxState.hideRightCnFlag = true;
    }, 200);
  } else {
    // 展开时
    setTimeout(() => {
      // 延时控制，解决展开时横向滚动条闪现问题
      rightBoxState.hideRightCnFlag = false;
    }, 200);
  }
};

const competeTypeChange = (val) => {
    selectedDom('competitionLeaseType')
};

// 房源弹窗
const LeaseHouseDialogRef = ref(null);
const showHousingDialog = () => {
  LeaseHouseDialogRef.value.open(form.assetsId,form.signType);
};

// 资产弹窗
const LeaseAssetDialogRef = ref(null);
const showAssetDialog = () => {
  LeaseAssetDialogRef.value.open();
};

// 承租方
const TenantryDialogRef = ref(null);
const showTenantryDialog = (className) => {
  TenantryDialogRef.value.showTenantryDialog();
  selectedDom(className);
};

// 租赁方信息
const getTenantryInfo = (row) => {
  let bool = false;
  form.leaseCustomers.forEach((item) => {
    if (item.customerId === row.customerId) {
      bool = true;
    }
  });
  if (bool) {
    ElMessage.warning(`不能选择相同客户!`);
    return;
  }
  form.leaseCustomers.push(row);
  form.haveCustomerValFlag = "已选择";
};
// 删除 租赁客户list
const doDeleteLeaseCustomersList = (index) => {
  form.leaseCustomers.splice(index, 1);
  if (form.leaseCustomers.length === 0) {
    form.haveCustomerValFlag = "";
  }
};

// 房源列表删除
const doDeletHousesList = (index) => {
  form.leaseHousings.splice(index, 1);
  if (form.leaseHousings.length === 0) {
    form.haveHousingValFlag = "";
  }
  getLeaseTotalArea();
};
// 保证金缴纳时间要在约定开始时间之前
const payDisabledDate = (time) => {
  if (form.openTime) {
    return dayjs(time) > dayjs(form.openTime);
  }
  return dayjs(time) < dayjs("2019-1-1");
};

// 约定开始时间要在保证金缴纳时间之后
const openDisabledDate = (time) => {
  if (form.depositPayTime) {
    return dayjs(time) < dayjs(form.depositPayTime);
  }
  return dayjs(time) < dayjs("2019-1-1");
};

/**
 * 付款方式
 */
const payTypeChange = () => {
    selectedDom('payType')
};

const signTypeChange = (val) => {
    selectedDom('signType');
};

// 跳转--->新租表单列表
const goCollaborativeApproval = () => {
  router.push({ path: "/asset/collaborativeApproval/createXinZhuForm/index" });
};

//保存并下一步
let contractTemplateId = router.currentRoute.value.params.contractTemplateId;
const emits = defineEmits(["nextStep"]);
const saveAndNext = () => {
  // 填充合同内容---> 保存
  let obj = {
    templateUrlKey: getTemplateUrlKey,
    param: JSON.parse(JSON.stringify(form)),
  };
  if(obj.param.fileOne!==null && obj.param.fileOne!==''){
      obj.param.fileOne = obj.param.fileOne.fileAddress;
  }
  if(obj.param.fileTwo!==null && obj.param.fileTwo!==''){
      obj.param.fileTwo = obj.param.fileTwo.fileAddress;
  }
  if(obj.param.fileThree!==null && obj.param.fileThree!==''){
      obj.param.fileThree = obj.param.fileThree.fileAddress;
  }
  obj.param.contractTemplateId = contractTemplateId;
    console.log('obj',obj);
  formRef.value.validate((vaild, fields) => {
    if (vaild) {
      contractApi2.bindData(obj).then((res) => {
        if (res.code === '200') {
          store.commit("SET_XIN_ZU_FORM", form);
          localSet("contractId", res.data);
          // emits("nextStep", "GoEdit");
          emits("nextStep", "GoSupplementaryForm");
        }
      });
    }
  });
};

const getAssetId = (val) => {
  form.assetsId = val.assetsId;
  form.assetsName = val.assetsName;
  form.address = val.address;
  form.leaseAsset = val.assetsName;
};

const getHouseInfo = (val) => {
  let i = form.leaseHousings.findIndex(x=>x.housingId===val.housingId);
  if(i!==-1){
      return ElMessage.warning('不能添加同一个房源!');
  }
  form.leaseHousings.push({
    housingId: val.housingId,
    leaseArea: val.area,
    areaUnitPrice: 0,
    housingNumber: val.housingNumber === null ? "" : val.housingNumber,
  });
  form.haveHousingValFlag = "已选择";
  getLeaseTotalArea();
};

//租赁开始/结束时间
const onSignTimeChange = (value) => {
  selectedDom('signStartTime')
  if (value && value !== "") {
    form.signStartTime = value[0];
    form.signEndTime = value[1];

    // 计算间隔月数
    const date1 = dayjs(value[0]);
    const date2 = dayjs(value[1]);
    form.signMonthlyRent = date2.diff(date1, "month", true).toFixed(1);

    if(form.signMonthlyRent===12 || form.signMonthlyRent > 12){
        return  form.term = (form.signMonthlyRent/12).toFixed(2)+'年';
    }
    form.term = form.signMonthlyRent + '月';
  }
};

/**
 * 租赁总面积
 */
const getLeaseTotalArea = () => {
    form.leaseTotalArea = 0;
    if (form.leaseHousings && form.leaseHousings.length !== 0) {
        form.leaseHousings.forEach((item) => {
            form.leaseTotalArea = form.leaseTotalArea + item.leaseArea;
        });
    }
}

// 租赁总面积
watch(form.leaseHousings, (value) => {
  form.leaseTotalArea = 0;
  if (value.length !== 0) {
    value.forEach((item) => {
      form.leaseTotalArea = form.leaseTotalArea + item.leaseArea;
    });
  }
},{deep:true,immediate:true});


/**
 * 监听form,用户在输入
 */
watch(form,(value)=>{
    store.commit("SET_XIN_ZU_FORM", form);
},{deep:true})

const getCompanyBank = () => {
  otherApi.getCompanyBank().then((res) => {
    form.payeeId = res.data[0].payeeId;
  });
};

const initForm = () => {
    console.log('store.state.collaborativeApproval.xinZuForm',store.state.collaborativeApproval.xinZuForm)
  if (store.state.collaborativeApproval.xinZuForm && JSON.stringify(store.state.collaborativeApproval.xinZuForm)!=='{}') {
      for (let key in store.state.collaborativeApproval.xinZuForm) {
          for (let key2 in form) {
                  if(store.state.collaborativeApproval.xinZuForm[key]){
                      form[key] = store.state.collaborativeApproval.xinZuForm[key];
                  }
          }
      }

  }
};

/**
 * 给dom添加class属性
 * @param el
 * @param className
 */
const addClass = (el, className) => {
    let oldClassStr = '';
    //先判断元素中是否有class属性
    if(el.getAttribute('class')){
        //获取原有的类名
        oldClassStr = el.getAttribute('class');
        //把原来的类名分割后添加入数组,判断要添加的类名是否已存在
        let oldClassArr = oldClassStr.split(' ');
        // 如果!=-1,说明存在或同名,不添加直接return
        if(oldClassArr.indexOf(className)!==-1){
            console.log(className+"已经存在或同名");
            return;
        }else{
            //添加空格
            oldClassStr+=' ';
        }
    }
    //添加新类名
    oldClassStr += className;
    el.setAttribute('class',oldClassStr);
}

/**
 * 创建dom节点
 */
const createDomNodes = () => {
    let previewBox = document.querySelector('.previewBox');
    let spanList = previewBox.getElementsByTagName('span');
    for (let span of spanList){
        addClass(span,'fontStyle');
        for (let key in form){
            if(span.innerText==='{{contactPhone}}'){
                addClass(span,'contactPhones');
            }
            let reg = new RegExp(key,'g');
            if(span.innerText.match(reg)){
                if(key === 'customerName' || key==='contactName'){ // 承租方(乙方) leaseCustomers  contactName:联系人
                    addClass(span,'leaseCustomers');
                }else{
                    addClass(span,key);
                }
            }
        }
    }
}

/**
 * 删除html中多余text
 */
const deleteDomText = () => {
  let textList = ['{{?leaseCustomers}}','{{/leaseCustomers}}','leaseCustomers','乙方：{{?leaseCustomers}}','{{customerName}}{{/leaseCustomers}}','{{?leaseHousings}}','{{/leaseHousings}}'];

    let previewBox = document.querySelector('.previewBox');
    let spanList = previewBox.getElementsByTagName('span');
    for (let span of spanList){
        for (let text of textList){
            if(span.innerText === text || span.innerText === '{{'+text+'}}' || span.innerText === '{{/'+text+'}}' || span.innerText === '{{?'+text+'}}'){
                if(span.innerText==='乙方：{{?leaseCustomers}}'){
                    span.innerText = '乙方：';
                }else if(span.innerText==='{{customerName}}{{/leaseCustomers}}'){
                    span.innerText = 'customerName';
                }else{
                    span.innerText = '';
                }
            }
        }
    }
}

/**
 * 选中dom 赋值,高亮
 */
const selectedDom = (className) => {
  let doms =  document.querySelectorAll('.'+className);
  let dom = doms.length===0?{}:doms[0];
    console.log('className',className);
    console.log('doms',doms)
    console.log('dom',dom)
  if(doms.length===0){
    return;
  }

  let domList = document.querySelectorAll('.fontStyle');
  for (let item of domList){
      item.style.background = '';
      item.style.fontWeight = 300;
      item.style.color = '#000000';
  }
  dom.style.background = 'yellow';
  dom.style.fontWeight = 600;
  dom.style.color = 'red';
  dom.scrollIntoView({behavior:"smooth",block:'center'});
}

const previewBoxRef = ref(null);

/**
 * 预览文档
 * @param fileName
 * @param res
 *
 */
const previewDocument= (fileName,res) => {
    const addTypeArray = fileName.split(".");
    const addType = addTypeArray[addTypeArray.length - 1]
    let params = {'docx':'docx','pdf':'pdf'};
    if(params[addType]){
        let blob = new Blob([res],{
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8'
        });
        // let blob = new Blob([res],{
        //     type: 'application/pdf;charset=UTF-8'
        // });

        if(params[addType]==='docx'){
            nextTick(()=>{
                renderAsync(blob, previewBoxRef.value);
            });
        }
        if(params[addType]==='pdf'){
            // 将blob转换为file
            let file = blobToFile(blob,new Date().getTime(),'application/pdf');
            // 将file转换为dataUrl
            let dataUrl = URL.createObjectURL(file);
            PDFObject.embed(dataUrl, '#demoDocContainer', { width: '100%' });
            setTimeout(()=>{
                URL.revokeObjectURL(dataUrl);
            },1000);
        }

    }
}


/**
 * 通过fileKey获取文件流预览docx文档
 * @param fileUrlKey
 * @param callback
 * @param err_callback
 */
const getWord = (fileUrlKey,callback,err_callback) => {
    reserveInvestmentProjectLibraryApi.getPlanWord({templateUrlKey:fileUrlKey}).then(res=>{
        if(res){
            // templateUrl
            previewDocument(fileUrlKey,res);
            if(callback)callback();
        }
        if(res.code!==undefined && res.code === '200'){
            if(err_callback)err_callback();
        }
    });
}

/**
 * 查询合同信息
 */
const getContractDraftVo = () => {
    contractApi.getContractDraftVo({contractId: getContractId})
        .then(res=>{
            getTemplateUrlKey = res.data.templateUrl;
            contractTemplateId = res.data.contractTemplateId;
            form.contractId = getContractId || res.data.contractId;
            const loading = ElLoading.service({
                lock: true,
                text: 'loading...',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            getWord(res.data.templateUrlKey,()=>{
                loading.close();
            },()=>{
                ElMessage.error('预览合同失败!')
                loading.close();
            });
        });
}

onMounted(() => {
  // initInfo();
  getCompanyBank();
  initForm();
  getContractDraftVo();
});
</script>

<style lang="scss" scoped>
.fillInTheContract-container {
  display: flex;
  justify-content: space-between;
  padding-bottom: 20px;
  .hide-contract-wrapper-width {
    width: 100% !important;
    transition: all 0.6s;
  }
  .show-contract-wrapper-width {
    width: calc(100% - 450px) !important;
    transition: all 0.6s;
  }
  .contract-wrapper {
    display: flex;
    flex-direction: column;
    .previewBox {
      border: 1px solid #e3e7f1;
      border-radius: 10px;
      padding: 36px 120px 30px;
      overflow-x: hidden;
      overflow-y: auto;
    }
    .button-wrapper {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 30px;
    }
  }

  .rightBox {
    border-left: 5px solid $title-sm-color;
    border-radius: 10px;
    padding: 30px 20px 30px 30px;
    position: relative;
    height:1200px;
    overflow-y:auto;
    :deep(.el-form) {
      .el-form-item {
        margin-bottom: 21px;
        .el-form-item__content {
          .selectStyle {
            width: 100%;
            .select-trigger {
              .el-input__wrapper {
                box-shadow: 0 0 0 1px $input-focus-bd-color inset;
              }
            }
          }
          .inputStyle {
            width: 100%;
            .el-input__wrapper {
              background-color: #fff8f6;
              box-shadow: 0 0 0 1px $input-focus-bd-color inset;
              .el-input__inner {
                text-align: center;
              }
            }
          }
          .inputCursor {
            .el-input__wrapper {
              .el-input__inner {
                cursor: pointer;
              }
            }
          }
        }
      }
      .modeItemBox {
        .el-form-item__content {
          .el-form-item {
            margin-bottom: 0;
            .el-form-item__content {
              .el-input {
                width: 54px;
                margin: 0 5px;
              }
            }
          }
        }
      }
      .limitInput {
        .el-form-item__content {
          display: flex;
          .dateRangeBox {
            margin-right: 6px;
            box-shadow: 0 0 0 1px $input-focus-bd-color inset;
          }
          .dateInputBox {
            flex: 1;
            .el-input__wrapper {
              box-shadow: 0 0 0 1px $input-focus-bd-color inset;
            }
          }
          .el-input {
            width: 100px;
          }
        }
      }
    }
    .ctrlBtnBox {
      width: 34px;
      height: 86px;
      line-height: 94px;
      text-align: center;
      padding-left: 10px;
      background: url("@/assets/iconImg/arrowbox.png") no-repeat;
      background-size: cover;
      position: absolute;
      top: 290px;
      cursor: pointer;
    }
    .toRightBtn {
      left: -39px;
    }
    .toLeftBtn {
      left: 14px;
    }
    .formHeadBox {
      font-size: 16px;
      font-family: SourceHanSansMedium;
      font-weight: 500;
      color: #1a1a1a;
      margin-bottom: 26px;
    }
  }

  .rightBox {
    :deep(.el-form) {
      .el-form-item {
        margin-bottom: 21px;
        .el-form-item__content {
          .selectStyle {
            width: 100%;
            // .select-trigger {
            //   .el-input__wrapper {
            //     box-shadow: 0 0 0 1px $input-focus-bd-color inset;
            //   }
            // }
          }
          .inputStyle {
            width: 100%;
            .el-input__wrapper {
              background-color: #fff8f6;
              //box-shadow: 0 0 0 1px $input-focus-bd-color inset;
              .el-input__inner {
                text-align: center;
              }
            }
          }
          .inputCursor {
            .el-input__wrapper {
              .el-input__inner {
                cursor: pointer;
              }
            }
          }
        }
      }
/*      .modeItemBox {
        .el-form-item__content {
          .el-form-item {
            margin-bottom: 0;
            .el-form-item__content {
              .el-input {
                width: 54px;
                margin: 0 10px;
              }
            }
          }
        }
      }*/
      .limitInput {
        .el-form-item__content {
          display: flex;
          .dateRangeBox {
            margin-right: 6px;
            //box-shadow: 0 0 0 1px $input-focus-bd-color inset;
          }
          .dateInputBox {
            flex: 1;
            .el-input__wrapper {
              width: 100%;
              //box-shadow: 0 0 0 1px $input-focus-bd-color inset;
            }
          }
          .el-input {
            width: 100px;
          }
        }
      }
    }
    .housesListBox {
      .housesItemStyle {
        position: relative;
        .el-form-item__content {
          display: flex;
          .deletBtn {
            position: absolute;
            z-index: 1;
            left: -71px;
            cursor: pointer;
          }
          .el-input {
            flex: 1;
            &:nth-child(2) {
              margin-right: 10px;
            }
          }
        }
      }
    }
  }

  .showRightWidth {
    //width: 428px;
    width: 500px;
    transition: all 0.6s;
  }
  .hideRightWidth {
    width: 0px;
    padding-left: 0;
    border-left: none;
    transition: all 0.6s;
  }
}
</style>
